package com.training.controller;

import com.training.entity.User; // Import User entity
import com.training.entity.Course; // Import Course entity
import com.training.entity.Chapter; // Import Chapter entity
import com.training.service.CourseService; // Import CourseService
import com.training.service.ChapterService; // Import ChapterService
import org.springframework.beans.factory.annotation.Autowired; // Import Autowired
import org.springframework.stereotype.Controller; // Import Controller
import org.springframework.ui.Model; // Import Model
import org.springframework.web.bind.annotation.GetMapping; // Import GetMapping
import org.springframework.web.bind.annotation.PostMapping; // Import PostMapping
import org.springframework.web.bind.annotation.RequestMapping; // Import RequestMapping
import org.springframework.web.bind.annotation.ModelAttribute; // Import ModelAttribute
import org.springframework.web.bind.annotation.PathVariable; // Import PathVariable
import org.springframework.web.servlet.mvc.support.RedirectAttributes; // Import RedirectAttributes
// 新增的导入
import org.springframework.web.bind.annotation.RequestParam; // 用于接收文件参数
import org.springframework.web.multipart.MultipartFile; // Spring 文件上传类型
// import org.springframework.util.StringUtils; // 可选：用于文件名处理，本例未使用但有时有用
import java.io.File; // 文件操作
import java.nio.file.Files; // 文件操作
import java.nio.file.Path; // 文件路径
import java.nio.file.Paths; // 文件路径
import java.io.IOException; // 异常处理
import java.util.UUID; // 用于生成唯一文件名


import javax.servlet.http.HttpSession; // Import HttpSession
import java.util.List; // Import List

@Controller
@RequestMapping("/chapter") // All requests in this controller will start with /chapter
public class ChapterController {

    @Autowired // Auto-inject ChapterService instance
    private ChapterService chapterService;

    @Autowired // Auto-inject CourseService instance (needed to get course details)
    private CourseService courseService;

    // 配置上传文件的目录。请根据你的实际项目结构修改此路径。
    // 注意：这里的路径是相对于项目运行的根目录。
    // 如果是Spring Boot jar包运行，这个路径可能是在jar包同级目录。
    // 建议在 application.properties 或 application.yml 中配置，这里为了示例直接写死。
    // 例如，如果你想让这些文件可以通过 /uploads/videos/xxx.mp4 访问，
    // 那么 UPLOAD_DIR 应该指向 Spring Boot 静态资源目录下的子目录，
    // 或者配置一个资源处理器。最简单的方式是直接在项目根目录创建此目录。
    private static final String UPLOAD_DIR = "uploads/videos/"; // 视频文件存储目录

    // 确保上传目录在控制器初始化时存在
    public ChapterController() {
        try {
            // 使用 Path 和 Files 确保目录存在
            Path path = Paths.get(UPLOAD_DIR); //
            if (!Files.exists(path)) { //
                Files.createDirectories(path); //
                System.out.println("Created upload directory: " + path.toAbsolutePath()); //
            } else {
                System.out.println("Upload directory already exists: " + path.toAbsolutePath()); //
            }
        } catch (IOException e) { //
            System.err.println("Failed to create upload directory: " + UPLOAD_DIR); //
            e.printStackTrace(); //
            // 考虑更健壮的错误处理，例如抛出运行时异常阻止应用启动
        }
    }


    /**
     * Display chapter management page for a specific course.
     * Corresponds to requirement FR-ZJGL-3 (view chapter basic information).
     * @param courseId Course ID
     * @param session HttpSession object to get logged-in user
     * @param model Model object to pass data to the page
     * @return Template name for the chapter management page
     */
    @GetMapping("/manage/{courseId}") // Respond to GET requests for /chapter/manage/{courseId}
    public String showChapterManagementPage(@PathVariable("courseId") Long courseId,
                                            HttpSession session,
                                            Model model,
                                            RedirectAttributes redirectAttributes) {
        // Check if user is logged in and is a teacher
        User loggedInUser = (User) session.getAttribute("loggedInUser"); //
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) { //
            return "redirect:/login"; //
        }

        // Get course details to display course name
        Course course = courseService.getCourseById(courseId); //
        if (course == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "课程不存在。"); //
            return "redirect:/course/manage"; // Redirect back to course management if course not found
        }

        // TODO: Validate if the current logged-in teacher has permission to manage chapters for this course
        //  (e.g., compare course.teaId with current teacher's ID)

        List<Chapter> chapters = chapterService.getChaptersByCourseId(courseId); //

        model.addAttribute("course", course); // Pass course object to the page
        model.addAttribute("chapters", chapters); // Pass chapter list to the page

        // Return templates/chapter-manage.html page
        return "chapter-manage"; //
    }

    /**
     * Display create chapter page for a specific course.
     * Corresponds to requirement FR-ZJGL-1.
     * @param courseId Course ID
     * @param session HttpSession object
     * @param model Model object
     * @return Template name for the create chapter page
     */
    @GetMapping("/create/{courseId}") // Respond to GET requests for /chapter/create/{courseId}
    public String showCreateChapterPage(@PathVariable("courseId") Long courseId,
                                        HttpSession session,
                                        Model model,
                                        RedirectAttributes redirectAttributes) {
        // Check if user is logged in and is a teacher
        User loggedInUser = (User) session.getAttribute("loggedInUser"); //
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) { //
            return "redirect:/login"; //
        }

        // Get course details to display course name
        Course course = courseService.getCourseById(courseId); //
        if (course == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "课程不存在。"); //
            return "redirect:/course/manage"; //
        }

        Chapter chapter = new Chapter(); //
        chapter.setCouId(courseId); // Set the course ID for the new chapter
        // Automatically set the next chapter order
        chapter.setChapterOrder(chapterService.getNextChapterOrder(courseId)); //

        model.addAttribute("course", course); // Pass course object
        model.addAttribute("chapter", chapter); // Pass empty chapter object for form binding

        // Return templates/create-chapter.html page
        return "create-chapter"; //
    }

    /**
     * Handle create chapter request.
     * Corresponds to requirement FR-ZJGL-1.
     * @param chapter Chapter object bound from the form
     * @param videoFile 上传的视频文件
     * @param session HttpSession object
     * @param redirectAttributes Used to pass messages after redirection
     * @return Redirect to the chapter management page
     */
    @PostMapping("/create") // Respond to POST requests for /chapter/create
    public String createChapter(@ModelAttribute Chapter chapter,
                                @RequestParam("videoFile") MultipartFile videoFile, // 接收文件
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        // Check if user is logged in and is a teacher
        User loggedInUser = (User) session.getAttribute("loggedInUser"); //
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) { //
            return "redirect:/login"; //
        }

        // 基本验证
        if (chapter.getChapterName() == null || chapter.getChapterName().trim().isEmpty()) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节名称不能为空。"); //
            return "redirect:/chapter/create/" + chapter.getCouId(); //
        }

        // 文件上传处理
        if (videoFile.isEmpty()) { //
            redirectAttributes.addFlashAttribute("errorMessage", "请选择要上传的视频文件。"); //
            return "redirect:/chapter/create/" + chapter.getCouId(); //
        }

        try {
            // 验证文件类型（可选，但推荐）
            if (!videoFile.getContentType().startsWith("video/")) { //
                redirectAttributes.addFlashAttribute("errorMessage", "上传的文件不是有效的视频格式。"); //
                return "redirect:/chapter/create/" + chapter.getCouId(); //
            }
            // 验证文件大小（可选，例如限制为 200MB）
            // if (videoFile.getSize() > 200 * 1024 * 1024) { // 200MB
            //     redirectAttributes.addFlashAttribute("errorMessage", "视频文件大小不能超过 200MB。");
            //     return "redirect:/chapter/create/" + chapter.getCouId();
            // }


            // 获取文件原始名称和扩展名
            String originalFilename = videoFile.getOriginalFilename(); //
            String fileExtension = ""; //
            if (originalFilename != null && originalFilename.contains(".")) { //
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); //
            }

            // 生成唯一的文件名，避免文件覆盖
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension; //
            // 构建完整的文件系统路径
            Path filePath = Paths.get(UPLOAD_DIR, uniqueFilename); //

            // 将文件保存到服务器
            Files.copy(videoFile.getInputStream(), filePath); //

            // 设置章节的URL为保存的文件路径
            // 注意：这里存储的是相对路径，前端通过这个路径来访问视频
            chapter.setChapterUrl("/" + UPLOAD_DIR + uniqueFilename); //

            chapterService.saveChapter(chapter); //
            redirectAttributes.addFlashAttribute("successMessage", "章节创建成功！"); //
        } catch (IOException e) { //
            e.printStackTrace(); //
            redirectAttributes.addFlashAttribute("errorMessage", "视频文件上传失败：" + e.getMessage()); //
            return "redirect:/chapter/create/" + chapter.getCouId(); //
        } catch (Exception e) { //
            e.printStackTrace(); //
            redirectAttributes.addFlashAttribute("errorMessage", "章节创建失败：" + e.getMessage()); //
        }

        // Redirect back to the chapter management page for the specific course
        return "redirect:/chapter/manage/" + chapter.getCouId(); //
    }

    /**
     * Display edit chapter page.
     * Corresponds to requirement FR-ZJGL-4.
     * @param id Chapter ID
     * @param session HttpSession object
     * @param model Model object
     * @return Template name for the edit chapter page
     */
    @GetMapping("/edit/{id}") // Respond to GET requests for /chapter/edit/{id}
    public String showEditChapterPage(@PathVariable("id") Long id,
                                      HttpSession session,
                                      Model model,
                                      RedirectAttributes redirectAttributes) {
        // Check if user is logged in and is a teacher
        User loggedInUser = (User) session.getAttribute("loggedInUser"); //
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) { //
            return "redirect:/login"; //
        }

        Chapter chapter = chapterService.getChapterById(id); //
        if (chapter == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节不存在。"); //
            return "redirect:/course/manage"; // Redirect to course management if chapter not found
        }

        // Get course details for display
        Course course = courseService.getCourseById(chapter.getCouId()); //
        if (course == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节所属课程不存在。"); //
            return "redirect:/course/manage"; //
        }

        model.addAttribute("course", course); // Pass course object
        model.addAttribute("chapter", chapter); // Pass chapter object for form binding

        // Return templates/edit-chapter.html page
        return "edit-chapter"; //
    }

    /**
     * Handle update chapter request.
     * Corresponds to requirement FR-ZJGL-4.
     * @param chapter Chapter object bound from the form
     * @param videoFile 上传的视频文件 (可选)
     * @param session HttpSession object
     * @param redirectAttributes Used to pass messages after redirection
     * @return Redirect to the chapter management page
     */
    @PostMapping("/edit") // Respond to POST requests for /chapter/edit
    public String updateChapter(@ModelAttribute Chapter chapter,
                                @RequestParam(value = "videoFile", required = false) MultipartFile videoFile, // 接收文件，可选
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        // Check if user is logged in and is a teacher
        User loggedInUser = (User) session.getAttribute("loggedInUser"); //
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) { //
            return "redirect:/login"; //
        }

        // Basic validation
        if (chapter.getId() == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节ID丢失，无法更新。"); //
            return "redirect:/course/manage"; //
        }
        if (chapter.getChapterName() == null || chapter.getChapterName().trim().isEmpty()) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节名称不能为空。"); //
            return "redirect:/chapter/edit/" + chapter.getId(); //
        }
        // 对于编辑，如果未上传新文件，且原URL为空，则需要处理
        // 或者从数据库加载原始章节信息，如果chapterUrl是从数据库加载而来，则其值会更准确。
        // 在前端 HTML 中，chapterUrl 字段作为 hidden input 传递了，所以这里通常不需要额外处理
        // 除非前端没有传，或者为了更严谨，可以从数据库重新查询
        Chapter existingChapter = chapterService.getChapterById(chapter.getId()); //
        if (existingChapter == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "要更新的章节不存在。"); //
            return "redirect:/chapter/manage/" + chapter.getCouId(); //
        }

        // 文件上传处理 (可选)
        if (videoFile != null && !videoFile.isEmpty()) { //
            try {
                // 验证文件类型（可选，但推荐）
                if (!videoFile.getContentType().startsWith("video/")) { //
                    redirectAttributes.addFlashAttribute("errorMessage", "上传的文件不是有效的视频格式。"); //
                    return "redirect:/chapter/edit/" + chapter.getId(); //
                }
                // 验证文件大小（可选）

                // 获取文件原始名称和扩展名
                String originalFilename = videoFile.getOriginalFilename(); //
                String fileExtension = ""; //
                if (originalFilename != null && originalFilename.contains(".")) { //
                    fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); //
                }

                // 生成唯一的文件名，避免文件覆盖
                String uniqueFilename = UUID.randomUUID().toString() + fileExtension; //
                // 构建完整的文件系统路径
                Path filePath = Paths.get(UPLOAD_DIR, uniqueFilename); //

                // 将文件保存到服务器
                Files.copy(videoFile.getInputStream(), filePath); //

                // 设置章节的URL为保存的文件路径
                chapter.setChapterUrl("/" + UPLOAD_DIR + uniqueFilename); // 注意这里加上了 / 作为相对路径的起始

                // 可选：如果旧视频文件存在，可以考虑删除它以释放空间
                if (existingChapter.getChapterUrl() != null && !existingChapter.getChapterUrl().trim().isEmpty()) { //
                    // 假设 chapterUrl 存储的是 /uploads/videos/xxx.mp4 这样的路径
                    // 需要转换为实际的文件系统路径
                    String oldFilePathStr = existingChapter.getChapterUrl().replaceFirst("/" + UPLOAD_DIR, UPLOAD_DIR); //
                    Path oldFilePath = Paths.get(oldFilePathStr); //
                    if (Files.exists(oldFilePath)) { //
                        try {
                            Files.delete(oldFilePath); //
                            System.out.println("Deleted old video file: " + oldFilePath); //
                        } catch (IOException e) { //
                            System.err.println("Failed to delete old video file: " + oldFilePath + " - " + e.getMessage()); //
                            // 不影响章节更新的主要流程，但记录错误
                        }
                    }
                }

            } catch (IOException e) { //
                e.printStackTrace(); //
                redirectAttributes.addFlashAttribute("errorMessage", "视频文件上传失败：" + e.getMessage()); //
                return "redirect:/chapter/edit/" + chapter.getId(); //
            }
        } else {
            // 如果没有上传新文件，则保留现有的 chapterUrl
            chapter.setChapterUrl(existingChapter.getChapterUrl()); //
        }

        // 如果章节名称为空，在编辑时也需要校验
        if (chapter.getChapterName() == null || chapter.getChapterName().trim().isEmpty()) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节名称不能为空。"); //
            return "redirect:/chapter/edit/" + chapter.getId(); //
        }
        // 如果章节URL最终还是为空（即没有旧的URL，也没有上传新的），则报错
        if (chapter.getChapterUrl() == null || chapter.getChapterUrl().trim().isEmpty()) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节地址不能为空或选择一个视频文件。"); //
            return "redirect:/chapter/edit/" + chapter.getId(); //
        }

        try {
            chapterService.saveChapter(chapter); // saveChapter method handles update when ID is present
            redirectAttributes.addFlashAttribute("successMessage", "章节更新成功！"); //
        } catch (Exception e) { //
            e.printStackTrace(); //
            redirectAttributes.addFlashAttribute("errorMessage", "章节更新失败：" + e.getMessage()); //
        }

        // Redirect back to the chapter management page for the specific course
        return "redirect:/chapter/manage/" + chapter.getCouId(); //
    }

    /**
     * Handle delete chapter request.
     * Corresponds to requirement FR-ZJGL-2.
     * @param id Chapter ID to delete
     * @param session HttpSession object
     * @param redirectAttributes Used to pass messages after redirection
     * @return Redirect to the chapter management page
     */
    @PostMapping("/delete/{id}") // Respond to POST requests for /chapter/delete/{id}
    public String deleteChapter(@PathVariable("id") Long id,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        // Check if user is logged in and is a teacher
        User loggedInUser = (User) session.getAttribute("loggedInUser"); //
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) { //
            return "redirect:/login"; //
        }

        // Retrieve chapter to get couId before deletion for redirection
        Chapter chapter = chapterService.getChapterById(id); //
        if (chapter == null) { //
            redirectAttributes.addFlashAttribute("errorMessage", "章节不存在或已被删除。"); //
            return "redirect:/course/manage"; //
        }
        Long couId = chapter.getCouId(); // Get course ID for redirection

        try {
            // 可选：在删除章节前，删除对应的视频文件
            if (chapter.getChapterUrl() != null && !chapter.getChapterUrl().trim().isEmpty()) { //
                String chapterUrl = chapter.getChapterUrl();
                // 检查 chapterUrl 是否以 UPLOAD_DIR (例如 /uploads/videos/) 开头，
                // 从而判断它是否是本地上传的文件路径
                if (chapterUrl.startsWith("/" + UPLOAD_DIR)) {
                    String filePathStr = chapterUrl.replaceFirst("/" + UPLOAD_DIR, UPLOAD_DIR); //
                    Path filePath = Paths.get(filePathStr); //
                    if (Files.exists(filePath)) { //
                        try {
                            Files.delete(filePath); //
                            System.out.println("Deleted video file: " + filePath.toAbsolutePath()); //
                        } catch (IOException e) { //
                            System.err.println("Failed to delete video file: " + filePath.toAbsolutePath() + " - " + e.getMessage()); //
                            // 不影响章节删除的主要流程，但记录错误
                        }
                    }
                } else {
                    System.out.println("Chapter URL is an external link, skipping local file deletion: " + chapterUrl);
                }
            }

            boolean success = chapterService.deleteChapter(id); //
            if (success) { //
                redirectAttributes.addFlashAttribute("successMessage", "章节删除成功！"); //
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "章节删除失败，请稍后再试。"); //
            }
        } catch (Exception e) { //
            e.printStackTrace(); //
            redirectAttributes.addFlashAttribute("errorMessage", "章节删除失败：" + e.getMessage()); //
        }

        // Redirect back to the chapter management page for the specific course
        return "redirect:/chapter/manage/" + couId; //
    }
}